package org.example.spirngmvcdemo.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;

@RestController
@RequestMapping("/request")
public class RequestController {

    // 通过 Servlet 提供的 HttpServletRequest 来获取 所有Cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();

        if(cookies != null) {
            Arrays.stream(cookies).forEach(cookie -> System.out.println(cookie.getName() + ": " + cookie.getValue()));
            return "获取 Cookie 成功";
        }
//        if (cookies != null) {
//            for(Cookie cookie : cookies) {
//                System.out.println(cookie.getName() + ": " + cookie.getValue());
//            }
//            return "获取 Cookie 成功";
//        }
        return "Cookie 为空";
    }

    // 通过 @CookieValue 获取某个 Cookie
    // 加上 @CookieValue 注解之后，前端必须 传 对应的 Cookie (就是键为 name 的 Cookie)
    // 否则 前端会 报 400 错误
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue String name) {
            System.out.println(name);
            return "获取 Cookie 成功";
    }

    // 通过 Servlet 提供的 HttpServletRequest 设置 Session
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("name", "lisi");
        return "设置 Session 成功";
    }

    // 通过 Servlet 提供的 HttpServletRequest 来获取 Session
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "name: " + name;
    }

    // 通过 SpringMVC 内置的 HttpSession 对象 来获取 Session
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        String name = (String) session.getAttribute("name");
        return "name: " + name;
    }

    // 通过 @SessionAttribute 来 获取 Session
    @RequestMapping("/getSession3")
    public String getSession3(@SessionAttribute String name) {
        return "name: " + name;
    }

    // 通过 HttpServletRequest 获取 Header 中的数据
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "User-Agent: " + userAgent;
    }

    // 通过 @RequestHeader 注解 获取 Header 中的内容
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String UserAgent) {
        return "User-Agent: " + UserAgent;
    }

}
